package leetcode.N301_N400;


import java.util.HashMap;
import java.util.Map;

public class N350 {

    public static void main(String[] args) {
        int [] nums1  = {1,2};
        int [] nums2  = {1,1};

        System.out.println(intersect(nums1, nums2).toString());
    }


    static int[] intersect(int[] nums1, int[] nums2) {
        int length1 = nums1.length;
        int length2 = nums2.length;
        int[] nums;
        int[] numLong;
        int length;
        if (length1 < length2) {
            nums = nums1;
            length = length1;
            numLong = nums2;
        } else {
            nums = nums2;
            length = length2;
            numLong = nums1;
        }
        Map<Integer, Integer> mapping = new HashMap<>(length * 4 / 3);

        for (int i : nums) {
            Integer value = mapping.get(i);
            if (value == null) {
                mapping.put(i, 1);
            } else {
                mapping.put(i, ++value);
            }
        }
        int[] result = new int[length];
        int index = 0;
        for (int i : numLong) {
            Integer value = mapping.get(i);
            if (value == null || value == 0) {
                continue;
            }
            mapping.put(i, --value);
            result[index++] = i;
        }

        if (index == length) {
            return result;
        }
        int[] r = new int[index];
        System.arraycopy(result, 0, r, 0, index);
        return r;
    }

}
